//
//  LockBindViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 31/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import PKHUD
import SwiftyJSON

class LockBindViewController: UITableViewController {

    @IBOutlet weak var lockMacAddrLabel: UILabel!
    @IBOutlet weak var lockNameTF: UITextField!
    @IBOutlet weak var lockNoteTV: UITextView!
    
    var device: BleDevice!
    var bleM: BLEFacade!
    var lockId: Int?
    var managerId: UInt32?
    var basecode = UInt32.randomPrime(length: 8)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavigationBarBack()
        checkLockStatus()
    }
    
    private func checkLockStatus() {
        HUD.show(.progress)
        bleM.checkLock(device: device) { [weak self] (info, error) in
            HUD.hide()
            if let e = error {
                HUD.flash(.label(e.errMsg), delay: 1.5)
            } else {
                self?.lockMacAddrLabel.text = info["macAddr"] as? String
                let status = info["status"] as? UInt8 ?? 0
                if self != nil && status == 1{
                    self?.bleM?.disconnectDevice()
                    HUD.flash(.label("该锁已被绑定"), onView: self!.view, delay: 1.5, completion: { _ in
                        self?.navigationController?.popViewController(animated: true)
                    })
                }
            }
        }
    }
    /// 绑定锁
    @IBAction func handleBindLockEvent(_ sender: UIButton) {
        // 先查询锁的状态
        let mac = lockMacAddrLabel.text!
        WNLockApi.findLock(lockId: nil, lockMac: mac).execute { (result: FxResponseResult<WNLockModel>) in
            switch result {
            case .success(let lock):
                if let _ = lock.id {
                    print("该锁:\(mac)已被绑定!")
                } else {
                    self.bindLock()
                }
                break
            case .failure(let error):
                HUD.flash(.label(error.errMsg), delay: 1.5)
            }
        }
        
        
    }
    private func bindLock() {
        let mac = lockMacAddrLabel.text!
        let model = 1
        let name = lockNameTF.text!
        let note = lockNoteTV.text!
        if let openId = self.managerId {
            bindLock_ble(openId: openId)
        } else {
            WNLockApi.bindLock(parameters: ["mac": mac,
                                            "model": model,
                                            "basecode": Int(basecode),
                                            "name": name,
                                            "note": note]
                ).execute { result in
                    switch result {
                    case .success(let json):
                        self.lockId = json["lock_id"].intValue
                        self.managerId = json["manager_id"].uInt32Value
                        self.bindLock_ble(openId: self.managerId!)
                        print("lockId: \(self.lockId!), managerId: \(self.managerId!)")
                    case .failure(let error):
                        HUD.flash(.label(error.errMsg), delay: 1.5)
                    }
            }
        }
        
    }
    /// 蓝牙绑定锁
    private func bindLock_ble(openId: UInt32) {
        
        bleM.bindLock(device: device, basecode: basecode, openId: openId) { [weak self] (info, error) in
            guard let code = info["code"] as? UInt8 else {
                return
            }
            if code == 1 {
                NotificationCenter.default.post(name: NSNotification.Name.WNLockAddNew, object: nil)
                HUD.flash(.labeledSuccess(title: "绑定成功", subtitle: nil), onView: self?.view, delay: 1.5, completion: { _ in
                    self?.navigationController?.popViewController(animated: true)
                })
            } else {
                let alertController = UIAlertController(title: "提示", message: "绑定失败，请确认蓝牙锁能正确连接", preferredStyle: .alert)
                let action = UIAlertAction(title: "确定", style: .default, handler: nil)
                alertController.addAction(action)
                self?.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return super.numberOfSections(in: tableView)
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return super.tableView(tableView, numberOfRowsInSection: section)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
